package com.example.auction.activity.mineActivity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.*;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.example.auction.R;
import com.example.auction.sqlite.Sqlite;
import com.example.auction.util.MyUtil;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class MineEditActivity extends AppCompatActivity {

    private TextView tvCencel;
    private Button btnEnterEdit;
    private ImageView ivUserImg;
    private EditText etUserpass;
    private EditText etNewUserpass;
    private Integer user_id;
    private byte[] image;
    private Sqlite sqlite;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mine_edit);

        findViewId();
        initData();
    }

    private void initData() {
        user_id = getIntent().getExtras().getInt("user_id");

        sqlite = new Sqlite(MineEditActivity.this);

        ivUserImg.setImageBitmap(MyUtil.getImageBySQL(
                MineEditActivity.this, "user", user_id));

        //从相册选择图片
        ivUserImg.setOnClickListener(new photoByAlbum());
        //完成
        btnEnterEdit.setOnClickListener(new enterEdit());
    }

    private void findViewId() {
        tvCencel = findViewById(R.id.tv_cencel);
        btnEnterEdit = findViewById(R.id.btn_enter_edit);
        ivUserImg = findViewById(R.id.iv_user_img);
        etUserpass = findViewById(R.id.et_userpass);
        etNewUserpass = findViewById(R.id.et_new_userpass);
    }

    //从相册选择图片
    private class photoByAlbum implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if (ContextCompat.checkSelfPermission(MineEditActivity.this,
                    //没有获得权限
                    Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                //重新申请权限
                ActivityCompat.requestPermissions(MineEditActivity.this, new
                        String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            } else {
                //已有权限
                //打开系统相册
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent, 1);
            }
        }
    }

    //返回从相册选择的图片
    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //获取图片路径
        if (requestCode == 1 && resultCode == Activity.RESULT_OK && data != null) {
            Uri selectedImage = data.getData();
            String[] filePathColumns = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(selectedImage, filePathColumns, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumns[0]);
            String imagePath = cursor.getString(columnIndex);
            try {
                showImage(imagePath);
//                Toast.makeText(this, "showImage", Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
                e.printStackTrace();
            }
            cursor.close();
        }
    }

    //加载图片
    private void showImage(String imaePath) throws IOException {
        Bitmap bm = BitmapFactory.decodeFile(imaePath);

        //创建一个字节数组输出流,流的大小为size
        int size = bm.getWidth() * bm.getHeight() * 4;
        ByteArrayOutputStream baos = new ByteArrayOutputStream(size);
        //设置位图的压缩格式，质量为100%，并放入字节数组输出流中
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        //将字节数组输出流转化为字节数组byte[]
        image = baos.toByteArray();
        ivUserImg.setImageBitmap(bm);
        baos.close();

    }

    private class enterEdit implements View.OnClickListener {
        @SuppressLint("Range")
        @Override
        public void onClick(View v) {
            String userPass = etUserpass.getText().toString().trim();
            String newUserPass = etNewUserpass.getText().toString().trim();
            long i = 0;
            long j = 0;

            if (image == null & userPass.equals("") & newUserPass.equals("")) {
                Toast.makeText(
                        MineEditActivity.this, "你还没有修改内容", Toast.LENGTH_SHORT).show();
            } else {
//            if (image != null | !userPass.equals("") | !newUserPass.equals("")){
                if (image != null) {
                    i = sqlite.updateUserImage(user_id, image);
                }

                //其中一个不为空提示
                if (!userPass.equals("") | !newUserPass.equals("")) {
                    if (userPass.equals("")) {
                        Toast.makeText(MineEditActivity.this, "请填写原密码", Toast.LENGTH_SHORT).show();
                    } else if (newUserPass.equals("")) {
                        Toast.makeText(MineEditActivity.this, "请填写新密码", Toast.LENGTH_SHORT).show();
                    }
                }
                //全都不为空时比对密码
                if (!userPass.equals("") & !newUserPass.equals("")) {
                    Cursor cursor = sqlite.selectUser(user_id);

                    if (userPass.equals(newUserPass)){
                        Toast.makeText(
                                MineEditActivity.this, "新密码不能和原密码一致", Toast.LENGTH_SHORT).show();
                    }else if (cursor != null && cursor.moveToFirst()) {
                        //原密码错误
                        if (!(userPass.equals(cursor.getString(cursor.getColumnIndex("user_pass"))))) {
                            Toast.makeText(MineEditActivity.this, "原密码错误", Toast.LENGTH_SHORT).show();
                        } else {
                            j = sqlite.updateUser(user_id, "user_pass", newUserPass);
                        }
                    }
                }
                if (i + j > 0) {
                    Toast.makeText(MineEditActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                    MineEditActivity.this.finish();
                }
            }
        }
    }
}